<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test page</title>
    <script src="/static/scripts/echarts.min.js"></script>
    <script src="/static/scripts/jquery-1.10.2.min.js"></script>
</head>

<body>
    <div id="app">
        <div>
            <!-- <button onclick="update_data_by_ajax()">Update by Server Logs</button> -->
        </div>
        <div>
            Upload logs
            <input type="file" class="form-control-file" style="margin-bottom: 3px" id="log_files" multiple="multiple" />
        </div>
        <div id="main" style="width: 1000px;height:600px;"></div>
    </div>
    <script type="text/javascript">
        var myChart = echarts.init(document.getElementById('main'));

        function renderItem(params, api) {
            var categoryIndex = api.value(0);
            var start = api.coord([api.value(1), categoryIndex]);
            var end = api.coord([api.value(2), categoryIndex]);
            var height = api.size([0, 1])[1] * 0.6;

            return {
                type: 'rect',
                shape: echarts.graphic.clipRectByRect({
                    x: start[0],
                    y: start[1] - height / 2,
                    width: end[0] - start[0],
                    height: height
                }, {
                        x: params.coordSys.x,
                        y: params.coordSys.y,
                        width: params.coordSys.width,
                        height: params.coordSys.height
                    }),
                style: api.style()
            };
        };
        function seconds_to_str(val) {
            if (!val) {
                return '';
            }
            val = Math.round(val);
            var hr = Math.floor(val / 3600);
            var min = Math.floor((val - hr * 3600) / 60);
            var sec = val % 60;
            var s = '';
            if (hr) {
                s += hr + 'h';
            }
            if (hr == 0 && min == 0) {
                // don't show: 0mxxs
            } else {
                s += min + 'm';
            }
            if (sec) {
                s += sec + 's';
            }
            return s;
        }
        option = {
            tooltip: {
                formatter: function (params) {
                    if (!params.value) {
                        return '';
                    }
                    var s = seconds_to_str(params.value[3]);
                    return params.marker +
                        params.value[5] +
                        '<br/>count: ' + params.value[4] +
                        ', time : ' + s;
                },
            },
            title: {
                text: 'Cycle Time',
                left: 'center'
            },
            legend: {
                // TODO: why not show
                show: true,
                type: 'plain',
                align: 'left',
                data: [],
                formatter: function (name) {
                    return 'Legend ' + name;
                }
            },
            dataZoom: [{
                type: 'slider',
                filterMode: 'weakFilter',
                showDataShadow: false,
                bottom: 15,
                height: 10,
                borderColor: 'transparent',
                backgroundColor: '#e2e2e2',
                labelFormatter: '',
                handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
                handleSize: 20,
                handleStyle: {
                    shadowBlur: 6,
                    shadowOffsetX: 1,
                    shadowOffsetY: 2,
                    shadowColor: '#aaa'
                }
            }, {
                type: 'inside',
                filterMode: 'weakFilter'
            }
            ],
            visualMap: {
                dimension: 3,
                min: 0,
                max: 2000,
                range: [10, 600],
                calculable: true,
                top: 50,
                right: 0,
                itemHeight: 500,
                formatter: function (value) {
                    return seconds_to_str(value);
                }
            },
            xAxis: {
                min: 0,
                scale: true,
                minInterval: 60,
                axisLabel: {
                    formatter: function (val) {
                        return seconds_to_str(val);
                    }
                },
                splitLine: {
                    show: true,
                },
                axisPointer: {
                    type: 'line',
                    show: true,
                    label: {
                        show: true,
                        formatter: function (params) {
                            return seconds_to_str(params.value);
                        }
                    }
                }
            },
            yAxis: {
                splitLine: {
                    show: true,
                },
                axisPointer: {
                    type: 'line',
                    show: true,
                    label: {
                        show: false
                    }
                },
                data: []
            },
            series: [{
                type: 'custom',
                renderItem: renderItem,
                itemStyle: {
                    normal: {
                        opacity: 0.8
                    }
                },
                encode: {
                    x: [1, 2],
                    y: 0
                },
                data: [[0, 0, 0, 0]]
            }]
        };

        myChart.setOption(option);

        function update_data_by_ajax() {
            $.get('/ajax/log/summary')
                .done(function (data) {
                    myChart.hideLoading();
                    var mac_list = JSON.parse(data.mac_list);
                    option.series[0].data = [];
                    for (var idx = 0; idx < mac_list.length; idx++) {
                        update_data_of_mac(mac_list[idx], idx);
                    }
                })
                .fail(function (data) {
                    console.log('Error: ' + data);
                })
        }
        function update_data_of_mac(mac, idx) {
            $.get('/ajax/log/summary/' + mac)
                .done(function (data) {
                    plan = JSON.parse(data.plan);
                    if (plan == null) {
                        return;
                    }
                    set_data(plan, idx);
                })
                .fail(function (data) {
                    console.log('Error: ' + data);
                });
        }
        function update_data_by_files(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) {
                return;
            }
            option.legend.data = [];
            option.yAxis.data = []
            option.series[0].data = [];
            for (var idx = 0; idx < files.length; idx++) {
                read_file(files[idx], idx);
            };
        }
        function read_file(file, idx) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var result = e.target.result;
                var data;
                if (result == 'data:') {
                    data = '';
                } else {
                    data = atob(result.split(';')[1].split(',')[1]);
                }
                var plan = build_plan_from_file(file.name, data);
                set_data(plan, idx);
            };
            reader.readAsDataURL(file);
        }
        function build_plan_from_file(file_name, content) {
            var plan = {};
            var file_name_a = file_name.split('-');
            while (file_name_a.length < 5) {
                file_name_a.push('');
            }
            plan.client = {};
            plan.client.rack = file_name_a[0];
            plan.client.location = file_name_a[1];
            var mac = file_name_a[2];
            var pxe = file_name_a[3];
            plan.count = parseInt(file_name_a[4]);
            var log = [];
            content.split('\n').forEach(function (line, li) {
                line = line.trim();
                if (line == '' || line[0] == '#') {
                    return;
                }
                var line_a = line.split(',');
                log.push(
                    {
                        count: line_a[0],
                        dt: parseInt(line_a[1]),
                        time: line_a[2],
                    }
                )
            });
            plan.pxe_list = [];
            plan.pxe_list.push(
                {
                    pxe: pxe,
                    log: log
                }
            )
            return plan;
        }
        function set_data(plan, idx) {
            var pxe_list = plan.pxe_list;
            var data = [];

            var baseTime = 0;
            pxe_list.forEach(
                function (pxe) {
                    data = data.concat(
                        pxe.log.map(
                            function (i) {
                                return [
                                    idx,
                                    baseTime,
                                    baseTime += i.dt,
                                    i.dt,
                                    i.count,
                                    i.time
                                ];
                            }));
                });

            var legend = plan.client.rack + '/' + plan.client.location;
            option.legend.data[idx] = legend;
            option.yAxis.data[idx] = legend;
            option.series[0].data = option.series[0].data.concat(data);
            myChart.setOption(option);
        };
        $('#log_files')[0].addEventListener('change', update_data_by_files);
    // update_data_by_ajax();
    // var timer = setInterval(update_data_by_ajax, 5000);
    </script>
</body>